/*
 * @Description: 
 * @Autor: wanghuan
 * @Date: 2021-11-29 14:56:25
 * @LastEditors: wanghuan
 * @LastEditTime: 2021-12-13 17:41:20
 */


import Vue from "vue"
import axios from "axios"
import qs from 'qs'
import $_storage from "./storage"
import $_config from "./config"

import { MessageBox  } from 'element-ui'
// 是否提示去登录
let HTTP_NOTIC_LOGIN = false;

const service = axios.create({
  baseURL: $_config.api || process.env.VUE_APP_API,
  timeout: 1000 * 30,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

service.interceptors.request.use(
  config => {
      // 转换 params
    if( config.params ){
        config.params = qs.stringify( config.params )
    }
    // 附加 token
    const token= $_storage.getToken_local()
    if (token) {
      config.headers[$_config.header_tokenKey] = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

//
service.interceptors.response.use(
  response => {
    const { data } = response

    // 文件直接返回
    if (data && data instanceof Blob) {
      return data
    }

    if ( data.code  === $_config.httpCode_success) {
      return data
    } else {
      // 异常状态码拦截  
      // token无效  提示去登录
      if( data.code - 0 === $_config.http_tokenInvalid ){
        if( HTTP_NOTIC_LOGIN ){ return false }
        HTTP_NOTIC_LOGIN = true;
        /* MessageBox.alert(data.msg || "登录状态失效，请重新登录！",{
          confirmButtonText:"去登录"
          ,closeOnClickModal: false
          ,closeOnPressEscape: false
          ,showClose: false
        }).then(res=>{
          // 转回登录逻辑
        }).catch(err=>{
          console.log("登录提示取消");
          HTTP_NOTIC_LOGIN = false;
        }); */
      }
      return Promise.reject(new Error(data.msg || 'Error'))
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export function $_httpGet(url, params, option) {
  return service({
    method: 'get',
    url,
    params,
    ...option
  })
}

export function $_httpPost(url, data, option) {
  return service({
    method: 'post',
    url,
    data,
    ...option
  })
}

export function $_httpDelete(url, data, option) {
  return service({
    method: 'delete',
    url,
    data,
    ...option
  })
}

export function $_httpPut(url, data, option) {
  return service({
    method: 'put',
    url,
    data,
    ...option
  })
}


Object.assign( Vue.prototype,{
  $_httpGet
  ,$_httpPost
  ,$_httpPut
  ,$_httpDelete
})